package com.kayeah82.application.avatar.qq.controller;

import com.kayeah82.application.avatar.qq.component.SecurityService;
import com.kayeah82.application.avatar.qq.model.Avatar;
import com.kayeah82.application.avatar.qq.security.QQFrequencyFilter;
import com.kayeah82.application.avatar.qq.service.AvatarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author kayeah82
 * */
@Controller
public class AvatarController {

    private final AvatarService avatarService;
    private final SecurityService securityService;

    @Autowired
    public AvatarController(AvatarService avatarService, SecurityService securityService) {
        this.avatarService = avatarService;
        this.securityService = securityService;
    }

    @GetMapping(path = "/")
    public Object toIndex() {
        return "index.html";
    }

    @GetMapping(path = "/get")
    public void getQQAvatar(@RequestParam(value = QQFrequencyFilter.KEY_PARAM) String qq,
                            HttpServletResponse response) throws IOException {
        Avatar avatar = avatarService.getAvatar(qq);
        this.outputAvatar(response, avatar);
    }

    @GetMapping(path = "/update")
    public void updateQQAvatar(@RequestParam(value = QQFrequencyFilter.KEY_PARAM) String qq,
                               HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        securityService.authorize(request);
        Avatar avatar = avatarService.updateAvatar(qq);
        this.outputAvatar(response, avatar);
    }

    private void outputAvatar(HttpServletResponse response, Avatar avatar) throws IOException {
        response.setContentType(avatar.getType().toString());
        OutputStream output = response.getOutputStream();
        output.write(avatar.getImage());
        output.flush();
    }

}
